<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 搜索与添加 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            placeholder="请输入内容"
            clearable
            @clear="getUserList"
            v-model="userParams.query"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 表格区域 -->
      <el-table :data="this.userlist" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template v-slot="scope">
            <el-switch
              @change="userChangeState(scope.row)"
              v-model="scope.row.mg_state"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template v-slot="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="small"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="small"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="small"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userParams.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="userParams.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
      ref="addFormRef"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="addFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close="setRoleDialogClosed"
    >
      <div>
        <p>当前的用户：{{ userInfo.username }}</p>
        <p>当前的角色：{{ userInfo.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUser,
  modifyData,
  addUserAjax,
  editQueryAjax,
  editUserAjax,
  deleteAjax,
  getAssignRolesAjax,
  selectedRoleAjax
} from "@/utils/api";
export default {
  data() {
    return {
      /* ======================基本用户数据========================== */
      userParams: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      userlist: [],
      total: 0,
      /* ======================添加用户数据========================== */
      // 控制 对话框的显示影藏
      addDialogVisible: false,
      //   添加用户的表单数据
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      //   验证规则
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入用户邮箱", trigger: "blur" },
          {
            pattern:
              /^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/,
            message: "请输入正确的邮箱",
            trigger: "blur",
          },
        ],
        mobile: [
          { required: true, message: "请输入用户手机号", trigger: "blur" },
          {
            pattern:
              /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/,
            message: "请输入合法手机号/电话号",
            trigger: "blur",
          },
        ],
      },
      /* ======================修改用户数据========================== */
      // 修改用户对话框的显示影藏
      editDialogVisible: false,
      // 查询到的用户对象
      editForm: {},
      // 控制分配角色对话框显示影藏
      setRoleDialogVisible: false,
      // 需要被分配权限的角色用户信息
      userInfo: {},
      // 所有角色的数据列表
      rolesList: [],
      // 已选中的角色id
      selectedRoleId:''
    };
  },
  methods: {
    /* ======================获取用户方法========================== */
    // 获取用户信息
    async getUserList() {
      const userData = this.userParams;
      const { data: res } = await getUser(userData);
      // console.log(res);
      this.userlist = res.data.users;
      this.total = res.data.total;
    },
    // 监听pagesize改变的事件
    handleSizeChange(newSize) {
      //   console.log(newSize);
      this.userParams.pagesize = newSize;
      this.getUserList();
    },
    // 监听页码值得改变的事件
    handleCurrentChange(newPage) {
      //   console.log(newPage);
      this.userParams.pagenum = newPage;
      this.getUserList();
    },
    // 监听swatch 状态
    async userChangeState(userinfo) {
      const { data: res } = await modifyData(userinfo);
      // console.log(res);
      // if(res.meta.state !== 200){
      // data.mg_state = !data.mg_state;
      //     this.$message.success('操作失败！')
      // }
      this.$message.success("更新用户状态成功！");
    },
    /* ======================添加用户方法========================== */
    // 对话框关闭重置
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 点击按钮添加用户
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        // 可以发起添加请求了
        const { data: res } = await addUserAjax(this.addForm);
        // console.log(res);
        this.$message.success(res.meta.msg);
        this.addDialogVisible = false;
        this.getUserList();
      });
    },
    /* ======================修改用户方法========================== */
    // 展示修改用户对话框
    async showEditDialog(id) {
      // console.log(id);
      const { data: res } = await editQueryAjax(id);
      console.log(res);
      this.editForm = res.data;
      this.editDialogVisible = true;
    },
    // 修改用户重置
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    // 修改用户
    editUser() {
      // 预验证
      this.$refs.editFormRef.validate(async (vaild) => {
        if (!vaild) return;
        // 发起修改用户请求
        let id = this.editForm.id;
        const { data: res } = await editUserAjax(id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile,
        });
        // console.log(res);
        this.editDialogVisible = false;
        this.getUserList();
        this.$message.success(res.meta.msg);
      });
    },
    /* ======================删除用户方法========================== */
    // 根据id删除对应用户
    async removeUserById(id) {
      // 弹框询问
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      // 如果用户确认删除，则返回值为字符串confirm
      //如果用户取消了删除，则返回值为字符串 cancel
      console.log(confirmResult);

      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除！");
      }

      const { data: res } = await deleteAjax(id);
      this.$message.success("删除用户成功！");
      this.getUserList();
    },
    //  展示分配角色的对话框
    async setRole(userInfo) {
      this.userInfo = userInfo;
      // 在展示对话框之前获取角色表
      const { data: res } = await getAssignRolesAjax();
      this.rolesList = res.data;
      this.setRoleDialogVisible = true;
    },
    // 点击按钮分配角色
   async saveRoleInfo(){
      if(!this.selectedRoleId){
        return this.$message.error('请选择要分配的角色')
      }
      const {data:res} = await selectedRoleAjax(this.userInfo.id,{rid:this.selectedRoleId});

      this.$message.success(res.meta.msg);
      this.getUserList();
      this.setRoleDialogVisible = false
    },
    setRoleDialogClosed(){
      this.selectedRoleId = ''
      this.userinfo = {}
    }
  },
  created() {
    this.getUserList();
  },
};
</script>

<style lang="less" scoped>
</style>></style>
